package yxy.game.pm2.module.office;

import yxy.apple.util.redisson.RedisException;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;

public class OfficeModule extends PlayerModule {
	// bean===========================================================================
	private String changeHeroCode;// 重置中的武将code
	private int targetHeroId; // 重置后的武将id

	public String getChangeHeroCode() {
		return changeHeroCode;
	}

	public void setChangeHeroCode(String changeHeroCode) {
		this.changeHeroCode = changeHeroCode;
	}

	public int getTargetHeroId() {
		return targetHeroId;
	}

	public void setTargetHeroId(int targetHeroId) {
		this.targetHeroId = targetHeroId;
	}

	// func===========================================================================

	public void update() {
		if (getChangeHeroCode() == null || getTargetHeroId() == 0) {
			return;
		}
		Hero hero = Hero.get(getPlayerCode(), getChangeHeroCode());
		if (hero == null || hero.getStar() < 4 || hero.getStar() > 5) {
			try {
				if (tryLock()) {
					setChangeHeroCode(null);
					setTargetHeroId(0);
					set();
				}
			} catch (Exception e) {
			} finally {
				unlock();
			}
		}
	}

	// redis==========================================================================

	static private String key(String playerCode) {
		return String.format("PLAYER:%s:MODULE:OFFICE", playerCode);
	}

	public void set() {
		try {
			setv(key(getPlayerCode()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	public static OfficeModule get(String playerCode) {
		try {
			OfficeModule module = getv(key(playerCode));
			if (module == null) {
				module = MySQLCacheDAO.getV(key(playerCode), OfficeModule.class);
				if(module != null){module.set();}//把数据同步到redis
			}

			if (module == null) {
				module = create(playerCode);
			}
			module.update();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static OfficeModule create(String playerCode) {
		OfficeModule module = new OfficeModule();
		module.setPlayerCode(playerCode);
		module.update();
		return module;
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				OfficeModule officeModule = getv(key(playerCode));
				if (officeModule != null)MySQLCacheDAO.setV(key, officeModule);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}

}
